package com.gxc.interceptor;

import com.alibaba.fastjson.JSON;
import com.gxc.entity.User;
import java.util.Enumeration;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 登陆拦截器.
 *
 * @author 宫新程
 * @since 2018/12/3 4:35 PM
 */
public class LoginInterceptor implements HandlerInterceptor {

  private final Logger logger = LoggerFactory.getLogger(getClass());

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {
    String params = JSON.toJSONString(request.getParameterMap());
    logger.info("URL：{}", request.getRequestURL());
    logger.info("IP：{}", request.getRemoteAddr());
    logger.info("Params：{}", params);
    logger.info("User-Agent：{}", request.getHeader("User-Agent"));

    User user = (User) request.getSession().getAttribute("login_user");
    if (user == null) {
      response.sendRedirect("/toLogin");
      return false;
    }
    return true;
  }

  @Override
  public void postHandle(
      HttpServletRequest request,
      HttpServletResponse response,
      Object handler,
      ModelAndView modelAndView)
      throws Exception {}

  @Override
  public void afterCompletion(
      HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
      throws Exception {}
}
